let db = require("../../../db/db")
let rights_handler = require("../../rights_handler")
let process_def_handler = require("./process_def_handler")

let translte = async function (diagram_xml, process_config, id, name) {
	var xml2js = require('xml2js');
	var xmlParser = new xml2js.Parser({ explicitArray: false }); // xml -> json
	var jsonBuilder = new xml2js.Builder({
		xmldec: { 'version': '1.0', 'encoding': 'UTF-8' }
	}); // jons -> xml

	return new Promise(function (resolve, reject) {
		xmlParser.parseString(diagram_xml, async function (err, json) {
			if (err) {
				reject(err);
			}
			//console.log(json);
			//translate
			let definition=json["bpmn2:definitions"].$;
			definition["xmlns:flowable"]="http://flowable.org/bpmn";
			let process = json["bpmn2:definitions"]["bpmn2:process"].$;
			process.isExecutable = "true";
			process.name = name;
			let usertasks = json["bpmn2:definitions"]["bpmn2:process"]["bpmn2:userTask"];
			for(let task of usertasks){
				task.$["flowable:candidateUsers"]="${candidateUsers_"+task.$.id+"}";
			}
			var publish_xml = jsonBuilder.buildObject(json);
			//console.log(json2xml);
			resolve(publish_xml);
		});
	})
}

let handle = async function (action, data, login_info, req, res) {
	let user_id = login_info.user_id;
	switch (action) {
		case "save":
			{
				let id = data.id;
				let name = data.name;
				let diagram_xml = data.diagram_xml;
				let process_config = data.process_config;

				let user_id = login_info.user_id;
				let datamodel = 112; //数据模型
				let rights = await rights_handler.get_datamodel_data_rights(datamodel, user_id);
				if (!rights.改) {
					return (Error("没有此数据模型数据修改权限：ID " + datamodel));
				}

				let sql = "update bpm_process_def set ?,update_user=? where id=?;";
				let params = [{
					diagram: diagram_xml,
					config: JSON.stringify({
						process_config: process_config
					})
				}, user_id, id];
				let result = await db.update(sql, params);
				return "ok";
			}
			break;
		case "savepublish":
			{
				let id = data.id;
				let name = data.name;
				let diagram_xml = data.diagram_xml;
				let process_config = data.process_config;

				let user_id = login_info.user_id;
				let datamodel = 112; //数据模型
				let rights = await rights_handler.get_datamodel_data_rights(datamodel, user_id);
				if (!rights.改) {
					return (Error("没有此数据模型数据修改权限：ID " + datamodel));
				}

				//在发布之前需要对xml进行处理
				let publish_xml = await translte(diagram_xml, process_config, id, name);
				let result = await process_def_handler.deployment_create(id, publish_xml);
				let deployment_id = result.id;
				result = await process_def_handler.get_deployment_process_defs(deployment_id);
				
				let process_def_id=result.data[0].id;

				let sql = "update bpm_process_def set ?,update_user=? where id=?;update bpm_process_def set version=version+1 where id=?;";
				let params = [{
					diagram: diagram_xml,
					config: JSON.stringify({
						process_config: process_config
					}),
					publish: publish_xml,
					f_deployment_id: deployment_id,
					f_process_def_id: process_def_id
				}, user_id, id, id];
				await db.multiupdate(sql, params);

				return "ok";
			}
			break;
		default:
			return (Error('未知的action:' + action));
	}
}

module.exports = { handle };